﻿using System.Web.Mvc;
using AmazeUI.bll;
using AmazeUI.bll.GetModel;
using AmazeUI.bll.Open;
using AmazeUI.bll.Open.OpenModel;
using AmazeUI.bll.Open.Weixin;
using AmazeUI.bll.Open.WeixinPay;
using AmazeUI.db;
using AmazeUI.Imodel;
using Com;

using Ema.Filters;
using Ema.Models;
using Ema.Models.XtModel;
using Newtonsoft.Json;
using WebCommon;

namespace Ema.Controllers
{
    public class WxController : OpenController
    {
        /// <summary>
        /// 获取通知url
        /// </summary>
        private string GetJsNotify
        {
            get { return this.GetHostUrl + "/wx/jsnotify"; }
        }

        /// <summary>
        /// 支付信息
        /// </summary>
        private PayBll _payBll = new PayBll();

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
            this._payBll.Dispose();
            //this.OpenBll.Dispose();
        }

        /// <summary>
        /// 不需要点确定登录
        /// </summary>
        string returl = Config.GetString("wxloginscopeno");

        /// <summary>
        /// 需要点确定登录
        /// </summary>
        string returlscope = Config.GetString("wxloginscope");

        /// <summary>
        /// 登录向
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public ActionResult Login(string url, string scope = "0")
        {
            ViewBag.url = url; ViewBag.scope = scope;
            return View();
        }

        /// <summary>
        /// 登录向
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public ActionResult Login1(string url)
        {
            return Redirect(GetWx.LoginUrl(url, true));
        }

        /// <summary>
        /// 去登录
        /// </summary>
        /// <returns></returns>
        public ActionResult WxLogining(string url, string scope)
        {
            if (string.IsNullOrEmpty(scope) || scope == "0")
            {
                return Redirect(GetWx.LoginUrl(returl, false, url));
            }
            else
            {
                return Redirect(GetWx.LoginUrl(returlscope, true, url));
            }
        }
        /// <summary>
        /// 跳转( 需要用户同意)
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult Loginscope(string code, string state)
        {
            var ut = Wx.GetLoginaccess_token(code);
            if (ut.errcode == null)
            {
                return RedirectToAction("Setuser", "Wx", new { accesstoken = ut.access_token, openid = ut.openid, code, state });

            }
            else
            {
                base.Logset("Wx.Loginscope.error", ut.errcode + "|code:" + code);
                return this.Content("错误");
            }

        }


        /// <summary>
        /// 跳转(以登录过的，不需要用户同意)
        /// </summary>
        /// <param name="code">code</param>
        /// <returns></returns>
        public ActionResult LoginscopeNo(string code, string state)
        {

            var ut = Wx.GetLoginaccess_token(code);
            if (ut.errcode == null)
            {

                var wu = OpenBll.IsWxUser(ut.openid);
                if (wu == null)
                {
                    //用户没登录过，则调转手动授权
                    return RedirectToAction("wxlogining", "wx", new { url = state, scope = "1" });
                }
                else
                {
                    var xu = XtUserBll.GetModel(wu.XtUserId);
                    XtUserBll.LoginEna(xu.Id, GetIp);
                    this.GetAdmin = xu;

                    return RedirectToAction("userinfo", "wx", new { code, state });
                }
            }
            else
            {
                base.Logset("Wx.LoginscopeNo.error", ut.errcode + "|code:" + code);
                return this.Content("错误");
            }
        }

        /// <summary>
        /// 写入用户信息
        /// </summary>
        /// <param name="code">code</param>
        /// <returns></returns>
        public ActionResult Setuser(string accesstoken, string openid, string code, string state)
        {
            var wxuser = Wx.GetLoginUserinfo(accesstoken, openid);

            if (wxuser.errcode == null)
            {
                var openUser = OpenBll.IsWxUser(wxuser.openid);
                var uid = 0;
                if (openUser == null)
                {
                    //添加系统用户数据
                    wxuser.UsingIp = this.GetIp;
                    uid = XtUserBll.AddXtUser(wxuser);
                    //添加open用户数据 
                    OpenBll.SetWxUser(wxuser, uid);
                    XtUserBll.Dispose();
                }
                else
                {
                    uid = openUser.XtUserId;
                }
                var xb = new XtUserBll();
                xb.LoginEna(uid, GetIp);
                this.GetAdmin = xb.GetModel(uid);
                return RedirectToAction("UserInfo", "Wx", new { code, state });
            }
            else
            {
                base.Logset("Wx.Setuser.error", wxuser.errcode + "|openid:" + openid);
            }

            return this.Content("");
        }

        /// <summary>
        /// wx用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>

        public ActionResult UserInfo(string code, string state)
        {
            // this.Getcodeandstate = "&code=" + code + "&state=" + state;
            if (string.IsNullOrWhiteSpace(state))
            {
                return RedirectToAction("Index", "Article");
            }
            else
            {
                return Redirect(state);
            }

        }



        /// <summary>
        /// 获取订单支付
        /// </summary>
        /// <returns></returns>
        [WxValidate]
        public ActionResult Pay(string code, string state, int oid = 1)
        {
            var order = _payBll.GetPayOrder(oid);
            if (order != null)
            {
                var o2 = PayOrder2.ToPayOrder(order);
                return this.View(o2);
            }
            else
            {
                return this.RedirectToAction("Sorry", "Goods");
            }

        }

        /// <summary>
        /// 获取微信信息
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns> 

        public ActionResult GetConfig(string url)
        {
            return this.GetJsonDb(new WxConfig(this.GetWx, this.WxSignature(url))
            {
                jsApiList = new[] { "checkJsApi", "onMenuShareTimeline", "showAllNonBaseMenuItem", "chooseImage", "uploadImage", "previewImage", "downloadImage","onMenuShareTimeline", "onMenuShareAppMessage",
"onMenuShareQQ","onMenuShareQZone","onMenuShareWeibo", }
            });
        }

        /// <summary>
        /// 获取微信支付信息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="oid"></param>
        /// <returns></returns> 
        [WxValidate]
        public ActionResult GetPayConfig(string url, int oid)
        {

            var id = this.GetAdmin.Id;
            var openUser = OpenBll.GetOpenUser(id);
            var model = _payBll.GetPayOrder(oid);

            var wp = new WxPackage(model, openUser.openid,"");

            var substring = wp.Substring();

            var postUrl = wp.PostUrl(substring);

            var packageId = wp.GetPackageId(postUrl);

            if (packageId == "")
            {
                base.Logset("wx.pay.substring", substring);
                base.Logset("wx.pay.postUrl", postUrl);
                return this.GetJsonDb(@"出错了，");
            }
            else
            {
                var wxPayConfig = new WxPayConfig(new WxConfig(wp, this.WxSignature(url)), packageId);
                base.Logset("wx.pay.model", JsonConvert.SerializeObject(model));

                return this.GetJsonDb(wxPayConfig);
            }
        }



        /// <summary>
        /// 获取微信收货地址
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns> 
        [WxscopeValidate]
        public ActionResult GetAddressConfig(string url)
        {
            var wxa = new WxAddressConfig(this.GetWx, this.WxSignature(url), url, this.GetaccessToken());
            return this.GetJsonDb(wxa);
        }

        /// <summary>
        /// 通知返回
        /// </summary>
        /// <returns></returns>
        public ActionResult JsNotify()
        {
            var inputStream = this.Request.InputStream;

            var nm = WxNotifyPayLogModel.GetNotifyModel(inputStream);

            if (string.IsNullOrWhiteSpace(nm.err_code))
            {
                var b = _payBll.SetNotify(nm);
                if (b)
                {
                    return this.Content(WxNotifyPayLogModel.retok);
                }
                else
                {
                    base.Logset("微信通知返回NO", "重复支付");
                    return this.Content(WxNotifyPayLogModel.retno);
                }

            }

            var str = WxNotifyPayLogModel.GetNotify(inputStream);
            base.Logset("微信通知返回NO", str);
            return this.Content(WxNotifyPayLogModel.retno);

        }
    }
}
